// pages/machinedetail/machinedetail.js
var utils = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    url: '',
    serial: '',
    machineInfo: null,
    service: [],
    files: [],
    accessoryDescribe: '',
    repairRecordRemark: '',
    faultDescribe: '',
    showSuccess:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      url: getApp().globalData.url,
      userInfo: getApp().globalData.yukaiUser,
      serial: options.serial
    });
    console.log(getApp().globalData.formId);
    this.getInfo(options.serial);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }, 
  inputFault: function (e) {
    this.setData({
      faultDescribe: e.detail.value
    });
  },
  inputRemark: function (e) {
    this.setData({
      repairRecordRemark: e.detail.value
    });
  },
  inputAccessory: function (e) {
    this.setData({
      accessoryDescribe: e.detail.value
    });
  },
  getInfo: function (serial) {
    wx.showLoading({});
    var userInfo = this.data.userInfo ? this.data.userInfo : getApp().getUser();
    var url = this.data.url ? this.data.url : getApp().getUrl();
    var _self = this;
    wx.request({
      url: url + '/equipment/findByEquipmentSerial',
      data: {
        token: userInfo.token,
        equipmentSerial: serial
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var data = res.data;
        switch (data.code) {
          case 200:
            var info = _self.convert(data.obj);
            _self.setData({
              machineInfo: info,
              service: info.serviceScope,
              accessoryDescribe: '',
              repairRecordRemark: '',
              faultDescribe: '',
              errorCode: ''
            });
            wx.hideLoading();
            break;
          case 412:
            wx.hideLoading();
            utils.alertBox(data.msg);
            break;
          case 422:
            wx.hideLoading();
            utils.toLogin();
            break;
          default:
            wx.hideLoading();
            break;
        }
      },
      fail: function () {
        wx.hideLoading();
        utils.alertBox('请求失败，请检查网络');
      }
    });
  },
  apply: function (e) {
    var _self = this;
    wx.showModal({
      title: '提示',
      content: '是否申请维修？',
      success: function (res) {
        if (res.confirm) {
          if (!utils.reg.isNull(_self.data.accessoryDescribe) || !utils.reg.isNull(_self.data.faultDescribe) ||
            !utils.reg.isNull(_self.data.repairRecordRemark) ) {
            utils.alertBox('请将信息填写完整');
            return;
          }
          wx.showLoading({});
          var formId = (getApp().globalData.formId)[0] + '-' + e.detail.formId;
          var userInfo = _self.data.userInfo;
          var url = _self.data.url;
          var machineInfo = _self.data.machineInfo;
          var data = {
            token: userInfo.token,
            staffId: userInfo.staffId,
            staffName: userInfo.name,
            hospitalName: machineInfo.hospitalName,
            departmentName: machineInfo.departmentName,
            equipmentName: machineInfo.name,
            equipmentSerial: _self.data.serial,
            eqiupmentModel: machineInfo.equipmentModel,
            accessoryDescribe: _self.data.accessoryDescribe,
            repairRecordRemark: _self.data.repairRecordRemark,
            faultDescribe: _self.data.faultDescribe,
            faultPhoto: _self.joinPhoto(),
            formId: formId
          };
          wx.request({
            url: url + '/repairRecord/add',
            data: data,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              var data = res.data;
              console.log(res.data);
              switch (data.code) {
                case 200:
                  _self.setData({
                    record: data.obj,
                    showSuccess:true
                  });
                  getApp().globalData.formId = [];
                  wx.hideLoading();
                  break;
                case 412:
                  wx.hideLoading();
                  utils.alertBox(data.msg);
                  break;
                case 422:
                  wx.hideLoading();
                  utils.toLogin();
                  break;
                default:
                  wx.hideLoading();
                  break;
              }
            },
            fail: function () {
              wx.hideLoading();
              utils.alertBox('请求失败，请检查网络');
            }
          });
        }
      }
    })
  },
  //适配数据
  convert: function (obj) {
    var newObj = {};
    newObj.hospitalName = obj.hospitalName;
    newObj.departmentName = obj.departmentName;
    newObj.equipmentBrandName = obj.equipmentBrandName ? obj.equipmentBrandName : '暂无信息';
    newObj.equipmentModel = obj.equipmentModel ? obj.equipmentModel:'暂无信息';
    newObj.equipmentSerial = obj.equipmentSerial;
    newObj.name = obj.name;
    newObj.beyondService = obj.beyondService;
    newObj.serviceScope = [];
    newObj.serviceYear = obj.serviceYear;
    newObj.enableDate = utils.formatTime(new Date(obj.enableDate));
    if (obj.serviceScope) {
      var serviceScope = JSON.parse(obj.serviceScope);
      for (var i = 0; i < serviceScope.length; i++) {
        serviceScope[i].icon = this.data.url + '/resource/images/equipmentServe/' + serviceScope[i].icon
      }
      newObj.serviceScope = serviceScope;
    }
    return newObj;
  },
  //打开设备描述详情
  open: function () {
    var service = [];
    for (var i = 0; i < this.data.service.length; i++) {
      var description = this.data.service[i].description ? this.data.service[i].description : '暂无描述';
      service.push(this.data.service[i].name + '：' + description);
    }
    wx.showActionSheet({
      itemList: service,
      success: function (res) {
        if (!res.cancel) {
          console.log(res.tapIndex)
        }
      }
    });
  },
  //上传图片
  chooseImage: function (e) {
    var that = this;
    var userInfo = this.data.userInfo;
    wx.chooseImage({
      count: 5,//一次最多上传5张
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        var files = that.data.files;
        for (var i = 0; i < tempFilePaths.length; i++) {
          //启动上传等待中...  
          wx.showLoading({
            title: '上传中'
          });
          wx.uploadFile({
            url: that.data.url + '/repairRecord/uploadRepairPhoto',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              token: userInfo.token
            },
            success: function (res) {
              var data = JSON.parse(res.data);
              //do something
              wx.hideLoading();
              var src = data.obj.split('-')[0];
              files.push(that.data.url + '/resource/images/repair_remark/' + src);
              that.setData({
                files: files
              });
            },
            fail: function () {
              utils.alertBox('图片上传失败，请重试');
            }
          })
        }
      }
    })
  },
  //预览图片
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  //删除照片
  deleteImage: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否删除照片',
      success: function (res) {
        if (res.confirm) {
          var files = that.data.files;
          files.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            files: files
          });
        }
      }
    })
  },
  joinPhoto: function () {
    var photo = '';
    var files = this.data.files;
    for (var i = 0; i < files.length; i++) {
      photo += files[i] + '-';
    }
    return photo;
  }
})